import importlib.util
import sys
import requests
import datetime
import pytz
import re
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
from tkinter import font


# 检查依赖库（仅检查不安装）
def check_dependencies():
    """检查必要的依赖库是否已安装"""
    libraries = ["requests", "pytz"]
    missing = []

    for lib in libraries:
        try:
            importlib.import_module(lib)
        except ImportError:
            missing.append(lib)

    if missing:
        messagebox.showerror("依赖缺失",
                             f"缺少必要的库: {', '.join(missing)}\n请在运行前安装: pip install {' '.join(missing)}")
        return False
    return True


# 验证邮箱格式
def validate_email(email):
    """验证邮箱格式是否正确"""
    pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
    return re.match(pattern, email) is not None


# 验证数量是否为正整数
def validate_count(count):
    """验证数量是否为正整数"""
    try:
        return int(count) > 0
    except ValueError:
        return False


class ZeppLifeApp:
    def __init__(self, root):
        self.root = root
        self.root.title("ZeppLife数据提交器(接口维护20:00-6:00)")
        self.root.geometry("600x500")
        self.root.resizable(True, True)

        # 设置中文字体
        self.default_font = font.nametofont("TkDefaultFont")
        self.default_font.configure(family="SimHei", size=10)
        self.root.option_add("*Font", self.default_font)

        # 创建主框架
        self.main_frame = ttk.Frame(root, padding="20")
        self.main_frame.pack(fill=tk.BOTH, expand=True)

        # 创建标题
        ttk.Label(self.main_frame, text="ZeppLife数据提交器(接口维护20:00-6:00)",
                  font=("SimHei", 16, "bold")).grid(row=0, column=0, columnspan=2, pady=10)

        # 创建输入区域
        input_frame = ttk.LabelFrame(self.main_frame, text="账号信息", padding="10")
        input_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=10)

        # 邮箱输入
        ttk.Label(input_frame, text="邮箱:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.email_var = tk.StringVar()
        self.email_entry = ttk.Entry(input_frame, textvariable=self.email_var, width=40)
        self.email_entry.grid(row=0, column=1, sticky=(tk.W, tk.E), pady=5)

        # 密码输入
        ttk.Label(input_frame, text="密码:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.password_var = tk.StringVar()
        self.password_entry = ttk.Entry(input_frame, textvariable=self.password_var,
                                        show="*", width=40)
        self.password_entry.grid(row=1, column=1, sticky=(tk.W, tk.E), pady=5)

        # 步数输入
        ttk.Label(input_frame, text="数据值:").grid(row=2, column=0, sticky=tk.W, pady=5)
        self.steps_var = tk.StringVar()
        self.steps_entry = ttk.Entry(input_frame, textvariable=self.steps_var, width=40)
        self.steps_entry.grid(row=2, column=1, sticky=(tk.W, tk.E), pady=5)

        # 设置列权重使输入框可扩展
        input_frame.columnconfigure(1, weight=1)

        # 创建操作按钮
        button_frame = ttk.Frame(self.main_frame)
        button_frame.grid(row=2, column=0, columnspan=2, pady=10)

        self.submit_button = ttk.Button(button_frame, text="提交", command=self.submit)
        self.submit_button.pack(side=tk.LEFT, padx=5)

        self.clear_button = ttk.Button(button_frame, text="清除", command=self.clear)
        self.clear_button.pack(side=tk.LEFT, padx=5)

        # 创建状态区域
        self.status_var = tk.StringVar()
        self.status_var.set("准备就绪")
        ttk.Label(self.main_frame, textvariable=self.status_var).grid(row=3, column=0,
                                                                      columnspan=2, sticky=tk.W)

        # 创建日志区域
        log_frame = ttk.LabelFrame(self.main_frame, text="操作日志", padding="10")
        log_frame.grid(row=4, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)

        self.log_text = scrolledtext.ScrolledText(log_frame, wrap=tk.WORD, height=10)
        self.log_text.pack(fill=tk.BOTH, expand=True)

        # 设置行和列的权重，使界面可缩放
        self.main_frame.columnconfigure(0, weight=1)
        self.main_frame.rowconfigure(4, weight=1)

        # 重定向print输出到日志区域
        self.old_stdout = sys.stdout
        sys.stdout = self

        # 检查依赖
        if not check_dependencies():
            self.root.destroy()

    def write(self, text):
        """重定向标准输出到日志区域"""
        self.log_text.insert(tk.END, text)
        self.log_text.see(tk.END)
        self.root.update_idletasks()

    def flush(self):
        """实现flush方法"""
        pass

    def submit(self):
        """处理提交请求"""
        # 获取用户输入
        email = self.email_var.get().strip()
        password = self.password_var.get().strip()
        steps = self.steps_var.get().strip()

        # 验证输入
        if not email:
            messagebox.showerror("输入错误", "请输入邮箱")
            return

        if not validate_email(email):
            messagebox.showerror("输入错误", "邮箱格式不正确")
            return

        if not password:
            messagebox.showerror("输入错误", "请输入密码")
            return

        if not steps:
            messagebox.showerror("输入错误", "请输入数据值")
            return

        if not validate_count(steps):
            messagebox.showerror("输入错误", "数据值必须是正整数")
            return

        # 获取当前时间（以北京时间为准）
        try:
            tz = pytz.timezone('Asia/Shanghai')
        except pytz.UnknownTimeZoneError:
            tz = pytz.utc
            print("使用UTC时区作为默认值")

        now = datetime.datetime.now(tz)
        hour = now.hour

        # 检查是否在允许的时间段内
        if 20 <= hour or hour < 6:
            messagebox.showinfo("时间限制", "接口维护时间，请在接口维护时间外提交")
            return

        # 更新状态
        self.status_var.set("正在提交请求...")
        self.submit_button.config(state=tk.DISABLED)
        self.root.update()

        # 构造API请求
        base_url = "https://api.mmp.cc/api/ZeppLife"
        params = {
            "user": email,
            "pass": password,
            "count": steps
        }

        try:
            # 发送带参数的GET请求
            print(f"正在发送请求到: {base_url}")
            response = requests.get(base_url, params=params)
            response.raise_for_status()  # 检查HTTP状态码

            # 尝试解析JSON响应
            try:
                data = response.json()
                print("API返回JSON数据:")
                print(data)
                self.show_result(data)
            except ValueError:
                # 如果不是JSON格式，返回原始文本
                print("API返回文本数据:")
                print(response.text)
                messagebox.showinfo("操作结果", response.text)

        except requests.exceptions.RequestException as e:
            print(f"网络请求错误: {e}")
            messagebox.showerror("请求失败", f"网络请求错误: {e}")
        except Exception as e:
            print(f"发生未知错误: {e}")
            messagebox.showerror("未知错误", f"发生未知错误: {e}")
        finally:
            # 恢复状态
            self.status_var.set("准备就绪")
            self.submit_button.config(state=tk.NORMAL)

    def show_result(self, data):
        """显示API返回的结果"""
        # 创建结果窗口
        result_window = tk.Toplevel(self.root)
        result_window.title("操作结果")
        result_window.geometry("500x400")
        result_window.resizable(True, True)

        # 设置中文字体
        result_font = font.nametofont("TkDefaultFont")
        result_font.configure(family="SimHei", size=10)
        result_window.option_add("*Font", result_font)

        # 创建结果文本区域
        result_text = scrolledtext.ScrolledText(result_window, wrap=tk.WORD)
        result_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 格式化并显示结果
        import json
        formatted_data = json.dumps(data, ensure_ascii=False, indent=4)
        result_text.insert(tk.END, formatted_data)
        result_text.config(state=tk.DISABLED)  # 设置为只读

        # 添加关闭按钮
        close_button = ttk.Button(result_window, text="关闭",
                                  command=result_window.destroy)
        close_button.pack(pady=10)

    def clear(self):
        """清除所有输入"""
        self.email_var.set("")
        self.password_var.set("")
        self.steps_var.set("")
        self.log_text.delete(1.0, tk.END)
        self.status_var.set("准备就绪")


def main():
    root = tk.Tk()
    app = ZeppLifeApp(root)
    root.mainloop()


if __name__ == "__main__":
    main()